﻿<%@ WebHandler Language="C#" Class="ApsPlanDownSendHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Configuration;

//Description: 排产下发回收处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-05-18
public class ApsPlanDownSendHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    LimitedCapacityBusiness m_LMObj = new LimitedCapacityBusiness();
    uLMSCommonIBusiness commonBusiness = uMESBusinessFactory.instance.GetuLMSCommonObject();
    ApsPlanDownSendBusiness apsPlanDownSendBusiness = new ApsPlanDownSendBusiness();
    TryLimitedCapacityBusiness tryAps = new TryLimitedCapacityBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetApsPlanListByPage": //获取排产下发列表数据（分页）
                    GetApsPlanListByPage(context);
                    break;
                case "SaveApsPlanDatas": //保存排产下发、回收、删除，
                    SaveApsPlanDatas(context);
                    break;
                case "SendHandApsDatas"://下发到手动排产
                    SendHandApsDatas(context);
                    break;
                case "GetResEmployee"://获取设备人员
                    GetResEmployee(context);
                    break;
                case "GetEditApsPlanResultDialogData"://获取编辑排产数据弹窗的初始化数据
                    GetEditApsPlanResultDialogData(context);
                    break;
                case "SaveApsPlanDetailData"://保存排产明细数据
                    SaveApsPlanDetailData(context);
                    break;
                case "IsSureSaveApsPlanDetail"://验证设备、人员的时间是否冲突
                    IsSureSaveApsPlanDetail(context);
                    break;
                //预排相关
                case "getTryApsPlanDetailData"://预排数据查询
                    GetTryApsPlanDetailData(context);
                    break;
                case "delTryApsPlanDetail"://预排数据删除
                    DelTryApsPlanDetail(context);
                    break;
                case "sendTryApsToHand"://发送预排数据到手动排产
                    SendHandApsDatas2(context);
                    break;
                case "updateTryPlanDetail"://修改预排产数据
                    UpdateTryPlanDetail(context);
                    break;
                //转工排产
                case "GetApsPlanShipListByPage": //获取转工排产下发列表数据（分页）
                    GetApsPlanShipListByPage(context);
                    break;
                case "SaveApsPlanShipDatas": //保存转工排产下发、回收
                    SaveApsPlanShipDatas(context);
                    break;
                case "GetApsPlanShipOperator": //获取转工排产下发时可选择的操作工
                    GetApsPlanShipOperator(context);
                    break;
                case "GetUserRole":
                    GetUserRole(context);
                    break;
                case "RefuseSendDown"://拒绝下发数据
                    RefuseSendDown(context);
                    break;
                case "GetDownLogData"://三天下发/回收审批日志
                    GetDownLogData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 选择员工后,获取设备资源
    /// </summary>
    /// <param name="context"></param>
    public void GetApsShipResourceInfo(HttpContext context)
    {
        string stremployeeids = context.Request.Form["employeeids"].ToString();
        DataTable dt = commonBusiness.GetResourceDefByemployeeid(stremployeeids);
        string[] array = new string[2];
        array[0] = "RESNAME";
        array[1] = "resourceid";
        DataTable newdt = dt.DefaultView.ToTable(true, array);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, DBTable = newdt }));
    }
    /// <summary>
    /// 选择班组后，获取操作工
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanShipOperator(HttpContext context)
    {
        string strSelectValue = context.Request.Form["teamID"].ToString();
        DataTable dt = new DataTable();
        Dictionary<string, string> para = new Dictionary<string, string>();
        if (strSelectValue == "0")
        {
            string strAttributes = commonBusiness.GetEnterpriseAttributes("工区长角色");

            para.Add("RoleName", strAttributes);
            para.Add("WorkCenterID", m_UserInfo.WorkCenterID);
            para.Add("FactoryID", m_UserInfo.FactoryID);
            dt = commonBusiness.GetEmployeeRoles(para);
            dt.Columns.Add("EMPLOYEEID");

            foreach (DataRow item in dt.Rows)
            {
                item["EMPLOYEEID"] = item["CHECKERID"];
            }

            dt.AcceptChanges();
        }
        else
        {
            dt = commonBusiness.GetEmployeeInfoByTeamId(strSelectValue);
        }

        dt.Columns.Add("RESOURCES");
        foreach (DataRow item in dt.Rows)
        {
            var temp = commonBusiness.GetResourceDefByemployeeid(" em.employeeid='" + item["EMPLOYEEID"].ToString() + "'");
            var resources = temp.DefaultView.ToTable(true, "RESNAME", "resourceid");
            item["Resources"] = JsonConvert.SerializeObject(resources);
        }

        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, DBTable = dt }));
    }
    /// <summary>
    /// 获取转工排产下发列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanShipListByPage(HttpContext context)
    {
        if (m_UserInfo.Factory.Contains("热表"))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "热表转工下发无权限" }));
            return;
        }
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        if (dic["status"] != "3" && dic["status"] != "1")
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "查询状态出错" }));
            return;
        }
        if (!string.IsNullOrWhiteSpace(dic["startTime1"]))
        {
            dic["startTime1"] = dic["startTime1"] + " 00:00:00";
        }
        if (!string.IsNullOrWhiteSpace(dic["startTime2"]))
        {
            dic["startTime2"] = dic["startTime2"] + " 23:59:59";
        }
        if (!string.IsNullOrWhiteSpace(dic["endTime1"]))
        {
            dic["endTime1"] = dic["endTime1"] + " 00:00:00";
        }
        if (!string.IsNullOrWhiteSpace(dic["endTime2"]))
        {
            dic["endTime2"] = dic["endTime2"] + " 23:59:59";
        }
        dic.Add("factory", m_UserInfo.FactoryID);//分厂
        uMESProcessResult result = apsPlanDownSendBusiness.GetApsPlanShipListByPage(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    private enum ApsPlanShipEnum { 下发, 回收 }
    /// <summary>
    /// 保存转工排产下发/回收
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanShipDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        ApsPlanShipEnum type = (ApsPlanShipEnum)int.Parse(context.Request["type"].ToString());
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择数据" }));
            return;
        }
        if (m_UserInfo.Factory.Contains("热表"))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "热表转工下发无权限" }));
            return;
        }
        switch (type)
        {
            case ApsPlanShipEnum.下发:
                Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
                DataTable operatorDatas = JsonConvert.DeserializeObject<DataTable>(context.Request["operatorDatas"].ToString());//操作工列表
                int valid = dt.AsEnumerable().Where(p => string.IsNullOrWhiteSpace(p["APSPLANEMPNAME"].ToString()) || string.IsNullOrWhiteSpace(p["RESOURCEDESC"].ToString())).Count();
                if (valid > 0 && (operatorDatas.Rows.Count == 0 || string.IsNullOrWhiteSpace(dic["resource"])))
                {
                    result.Result = false; result.Message = "请填写人员和设备";
                    break;
                }
                Dictionary<string, object> param = new Dictionary<string, object>();
                param.Add("workcenter", dic["workcenter"]);
                param.Add("team", dic["team"]);
                param.Add("resource", dic["resource"]);
                param.Add("operator", operatorDatas);
                param.Add("FactoryName", m_UserInfo.Factory);//操作人分厂
                result = apsPlanDownSendBusiness.SaveApsPlanShipSendData(dt, param, m_UserInfo);
                break;
            case ApsPlanShipEnum.回收:
                result = apsPlanDownSendBusiness.SaveApsPlanShipRecallData(dt, m_UserInfo);
                break;
            default:
                result.Result = false; result.Message = "未知功能";
                break;
        }

        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 修改预排产数据
    /// </summary>
    /// <param name="context"></param>
    public void UpdateTryPlanDetail(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());

        var sqlList = new ArrayList();
        var updateSql = @"update apsplandetailpre al set al.workcenterid='{0}',al.teamid='{1}',al.resourceid='{2}',
        al.starttime=to_date('{3}','yyyy/mm/dd hh24:mi:ss'),al.endtime=to_date('{4}','yyyy/mm/dd hh24:mi:ss'),
        al.resstarttime=to_date('{5}','yyyy/mm/dd hh24:mi:ss'),al.resendtime=to_date('{6}','yyyy/mm/dd hh24:mi:ss')
        where al.apsplandetailid='{7}'";
        foreach (DataRow row in dt.Rows)
        {
            sqlList.Add(string.Format(updateSql, row["workcenterid"].ToString(), row["teamid"].ToString(), row["resourceid"].ToString(), row["starttime"].ToString(),
                row["endtime"].ToString(), row["resstarttime"].ToString(), row["resendtime"].ToString(), row["apsplandetailid"].ToString()));
        }
        DatabaseHelper.ExecuteSqlListTran(sqlList);
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));

    }
    /// <summary>
    /// 下发到手动排产
    /// </summary>
    /// <param name="context"></param>
    public void SendHandApsDatas2(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择数据" }));
            return;
        }
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//操作人           
        uMESProcessResult result = apsPlanDownSendBusiness.SendHandApsDatas2(dic, dt);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 删除预排数据
    /// </summary>
    /// <param name="context"></param>
    public void DelTryApsPlanDetail(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());

        List<string> ids = new List<string>();

        foreach (DataRow dr in dt.Rows)
        {
            if (!ids.Contains(dr["apsplandetailId"].ToString()))
            {
                ids.Add(dr["apsplandetailId"].ToString());
            }
        }
        tryAps.DeleteApsPlanData(ids);

        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));

    }
    /// <summary>
    /// 获取排产列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetTryApsPlanDetailData(HttpContext context)
    {
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        DataRow dr = dt.Rows[0];
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("mfgOrderName", dr["mfgOrderName"].ToString());//件号
        dic.Add("containerName", dr["containerName"].ToString());//批次号
        dic.Add("productName", dr["productName"].ToString());//件号
        dic.Add("specNo", dr["specNo"].ToString());//工序号
        dic.Add("startTime", dr["startTime"].ToString());//开始时间
        dic.Add("endTime", dr["endTime"].ToString());//结束时间
        dic.Add("apsType", dr["apsType"].ToString());//排产策略 
        dic.Add("workCenter", dr["workCenter"].ToString());//工区
        dic.Add("team", dr["team"].ToString());//班组
        dic.Add("factory", m_UserInfo.FactoryID);//分厂
        dic.Add("PageIndex", pageNumber);//
        dic.Add("PageSize", pageSize);//
        uMESProcessResult result = apsPlanDownSendBusiness.GetTryApsPlanDetailData(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 验证设备、人员的时间是否冲突
    /// </summary>
    /// <param name="context"></param>
    public void IsSureSaveApsPlanDetail(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["param"].ToString());
        DataTable dtApsPlanDetail = JsonConvert.DeserializeObject<DataTable>(context.Request["apsPlanDetailDatas"].ToString());
        if (dtApsPlanDetail.Rows.Count == 0)
        {
            result.Result = false; result.Message = "缓存过期，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataTable dtResEmp = JsonConvert.DeserializeObject<DataTable>(context.Request["resEmp"].ToString());
        if (dtResEmp.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择人员数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string type = dtApsPlanDetail.Rows[0]["type"].ToString();//编辑类型（1：单次编辑，2：批量编辑）
        string[] items = { "resourceId", "workcenterId", "teamId", "apsPlanQty" };//需要验证的字段 "startDate", "endDate", "resStartDate", "resEndDate",
        if (items.Where(p => param.Keys.Contains(p) && string.IsNullOrWhiteSpace(param[p])).Count() > 0)
        {
            result.Result = false; result.Message = "请填写完整数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (param.Keys.Contains("apsPlanQty") && int.Parse(param["apsPlanQty"].ToString()) <= 0)
        {
            result.Result = false; result.Message = "排产数不得小于等于0";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["startDate"]) && string.IsNullOrWhiteSpace(param["endDate"]))
        {
            result.Result = false; result.Message = "排产结束日期不能为空";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(param["startDate"]) && !string.IsNullOrWhiteSpace(param["endDate"]))
        {
            result.Result = false; result.Message = "排产开始日期不能为空";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["startDate"]) && DateTime.Parse(param["startDate"]) > DateTime.Parse(param["endDate"]))
        {
            result.Result = false; result.Message = "排产开始日期大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["resStartDate"]) && DateTime.Parse(param["resStartDate"]) > DateTime.Parse(param["resEndDate"]))
        {
            result.Result = false; result.Message = "设备开始日期大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        foreach (DataRow item in dtApsPlanDetail.Rows)
        {
            string sql = string.Format(@"SELECT apd1.starttime,apd1.endtime,apd1.resendtime,apd1.resstarttime FROM apsplandetail apd 
                     LEFT JOIN apsplandetail apd1 ON apd1.containerid = apd.containerid 
                     WHERE apd.apsplandetailid = '{0}' AND apd1.apsplandetailid <> '{0}'", item["apsPlanDetailID"]);
            DataTable dtres = DatabaseHelper.Query_ReturnDatTable(sql);
            //如果排产开始日期大于填写的排产结束日期，排产结束日期同理，则不重叠
            if (!string.IsNullOrWhiteSpace(param["startDate"]))
            {
                Func<DataRow, bool> ex = p => DateTime.Parse(p["starttime"].ToString()) > DateTime.Parse(param["endDate"])
                    || DateTime.Parse(p["endtime"].ToString()) < DateTime.Parse(param["startDate"]);
                if (dtres.AsEnumerable().Where(ex).Count() != dtres.Rows.Count)
                {
                    result.Result = false; result.Message = "排产日期重叠，是否继续保存？"; result.ReturnData = "1";
                    break;
                }
            }
            //如果设备开始日期大于填写的设备结束日期，设备结束日期同理，则不重叠
            if (!string.IsNullOrWhiteSpace(param["resStartDate"]))
            {
                Func<DataRow, bool> ex = p => (!string.IsNullOrWhiteSpace(p["resstarttime"].ToString()) && DateTime.Parse(p["resstarttime"].ToString()) > DateTime.Parse(param["resEndDate"]))
                    || (!string.IsNullOrWhiteSpace(p["resendtime"].ToString()) && DateTime.Parse(p["resendtime"].ToString()) < DateTime.Parse(param["resStartDate"]));
                if (dtres.AsEnumerable().Where(ex).Count() != dtres.Rows.Count)
                {
                    result.Result = false; result.Message = "设备日期重叠，是否继续保存？"; result.ReturnData = "1";
                    break;
                }
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取编辑排产数据弹窗的初始化数据
    /// </summary>
    /// <param name="context"></param>
    public void GetEditApsPlanResultDialogData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtApsPlanDetail = JsonConvert.DeserializeObject<DataTable>(context.Request["apsPlanDetailDatas"].ToString());
        if (dtApsPlanDetail.Rows.Count == 0)
        {
            result.Result = false; result.Message = "请选择数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string workFlowID = dtApsPlanDetail.Rows[0]["WorkFlowID"].ToString();
        string workFlowStepID = dtApsPlanDetail.Rows[0]["WorkFlowStepID"].ToString();
        if (dtApsPlanDetail.AsEnumerable().Where(p => p["WorkFlowID"].ToString() != workFlowID || p["WorkFlowStepID"].ToString() != workFlowStepID).Count() > 0)
        {
            result.Result = false; result.Message = "请选择同工艺同工序的批次";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //获取工序设备信息
        DataTable dtRes = m_LMObj.Aps_GetSpecResourceDt(string.Format("'{0}'", dtApsPlanDetail.Rows[0]["specID"].ToString()));
        foreach (DataRow item in dtRes.Rows)
        {
            item["RESOURCENAME"] = string.Format("{0}（{1}）", item["RESOURCENAME"].ToString(), item["description"].ToString());
        }
        dtRes.TableName = "dtRes";
        result.DBDataSet.Tables.Add(dtRes);
        //获取排产人员
        DataTable dtEmp = new DataTable();
        if (dtApsPlanDetail.Rows.Count == 1)//如果只有一条数据，则查询该数据的排产人员
        {
            string sql = string.Format("SELECT ape.employeeid FROM apsplandetailemp ape WHERE ape.apsplandetailid = '{0}' AND ape.isuse = 0", dtApsPlanDetail.Rows[0]["ApsPlanDetailID"].ToString());
            dtEmp = DatabaseHelper.Query_ReturnDatTable(sql);
        }
        dtEmp.TableName = "dtEmp";
        result.DBDataSet.Tables.Add(dtEmp);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取设备的人员
    /// </summary>
    /// <param name="context"></param>
    public void GetResEmployee(HttpContext context)
    {
        if (context.Request["resourceId"] != null && string.IsNullOrWhiteSpace(context.Request["resourceId"].ToString()))
        {
            return;
        }
        var dt = m_LMObj.Aps_GetResEmpDt("'" + context.Request["resourceId"].ToString() + "'");
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }

    /// <summary>
    /// 保存排产详细数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanDetailData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["param"].ToString());
        DataTable dtApsPlanDetail = JsonConvert.DeserializeObject<DataTable>(context.Request["apsPlanDetailDatas"].ToString());
        if (dtApsPlanDetail.Rows.Count == 0)
        {
            result.Result = false; result.Message = "缓存过期，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataTable dtResEmp = JsonConvert.DeserializeObject<DataTable>(context.Request["resEmp"].ToString());
        if (dtResEmp.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择人员数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string type = dtApsPlanDetail.Rows[0]["type"].ToString();//编辑类型（1：单次编辑，2：批量编辑）
        string[] items = { "resourceId", "workcenterId", "teamId", "apsPlanQty" };//需要验证的字段"startDate", "endDate", "resStartDate", "resEndDate",
        if (items.Where(p => param.Keys.Contains(p) && string.IsNullOrWhiteSpace(param[p])).Count() > 0)
        {
            result.Result = false; result.Message = "请填写完整数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (param.Keys.Contains("apsPlanQty") && int.Parse(param["apsPlanQty"]) <= 0)
        {
            result.Result = false; result.Message = "排产数不得小于等于0";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["startDate"]) && string.IsNullOrWhiteSpace(param["endDate"]))
        {
            result.Result = false; result.Message = "排产结束日期不能为空";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(param["startDate"]) && !string.IsNullOrWhiteSpace(param["endDate"]))
        {
            result.Result = false; result.Message = "排产开始日期不能为空";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["startDate"]) && DateTime.Parse(param["startDate"]) > DateTime.Parse(param["endDate"]))
        {
            result.Result = false; result.Message = "排产开始日期大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["startDate"]) && DateTime.Parse(param["startDate"]) < DateTime.Now.AddMonths(-1))
        {
            result.Result = false; result.Message = "排产开始日期不得超过一月前";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["resStartDate"]) && DateTime.Parse(param["resStartDate"]) > DateTime.Parse(param["resEndDate"]))
        {
            result.Result = false; result.Message = "设备开始日期大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(param["resStartDate"]) && DateTime.Parse(param["resStartDate"]) < DateTime.Now.AddMonths(-1))
        {
            result.Result = false; result.Message = "设备开始日期不得超过一月前";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ArrayList list = new ArrayList();
        StringBuilder sql = new StringBuilder();
        foreach (DataRow drAps in dtApsPlanDetail.Rows)
        {
            //查询是否已下发
            sql.Clear();
            sql.AppendFormat("SELECT 1 FROM apsplandetail apd WHERE apd.apsplandetailid = '{0}' AND NVL(apd.status,'0') <> '1'", drAps["apsPlanDetailID"]);
            if (DatabaseHelper.GetSingle(sql.ToString()) == null && param["status"].Equals("0"))//未下发状态，已下发的不做校验，因为只修改设备、人员信息
            {
                result.Result = false; result.Message = "排产数据已下发或已删除，请重新查询";
                break;
            }
            //更新排产基础数据
            sql.Clear();
            //            sql.AppendFormat(@"
            //                        UPDATE apsplandetail apd
            //                        SET apd.workcenterid = '{0}',apd.teamid = '{1}',apd.resourceid = '{2}',{3}
            //                        apd.starttime = to_date('{4}','yyyy-MM-dd HH24:mi:ss'),
            //                        apd.endtime =  to_date('{5}','yyyy-MM-dd HH24:mi:ss'),
            //                        apd.resstarttime = to_date('{6}','yyyy-MM-dd HH24:mi:ss'),
            //                        apd.resendtime = to_date('{7}','yyyy-MM-dd HH24:mi:ss')
            //                        WHERE apd.apsplandetailid = '{8}' AND nvl(apd.status,0) <> '1'",
            //                        param["workcenterId"], param["teamId"], param["resourceId"], type == "1" ? string.Format("apd.qty = {0},", int.Parse(param["apsPlanQty"])) : "",
            //                        param["startDate"], param["endDate"], param["resStartDate"], param["resEndDate"], drAps["apsPlanDetailID"]);
            string updateColumns = string.Format("apd.resourceid = '{0}',", param["resourceId"]);
            updateColumns += type == "1" ? string.Format("apd.qty = {0},", int.Parse(param["apsPlanQty"])) : "";
            if (!string.IsNullOrWhiteSpace(param["startDate"])) { updateColumns += string.Format("apd.starttime = to_date('{0}','yyyy-MM-dd HH24:mi:ss'),", param["startDate"]); }
            if (!string.IsNullOrWhiteSpace(param["endDate"])) { updateColumns += string.Format("apd.endtime = to_date('{0}','yyyy-MM-dd HH24:mi:ss'),", param["endDate"]); }
            if (!string.IsNullOrWhiteSpace(param["resStartDate"])) { updateColumns += string.Format("apd.resstarttime = to_date('{0}','yyyy-MM-dd HH24:mi:ss'),", param["resStartDate"]); }
            if (!string.IsNullOrWhiteSpace(param["resEndDate"])) { updateColumns += string.Format("apd.resendtime = to_date('{0}','yyyy-MM-dd HH24:mi:ss'),", param["resEndDate"]); }
            sql.AppendFormat(@"
                        UPDATE apsplandetail apd
                        SET apd.workcenterid = '{0}',apd.teamid = '{1}',{2}
                        WHERE apd.apsplandetailid = '{3}' AND nvl(apd.status,0) <> '1'"
                        , param["workcenterId"], param["teamId"], updateColumns.TrimEnd(','),
                        drAps["apsPlanDetailID"]);
            list.Add(sql.ToString());
            //更新排产人员
            var containerstepdispatchid = DatabaseHelper.GetSingle(string.Format(@"select c.containerstepdispatchid from apsplandetail aps 
                        left join containerstepdispatch c on c.containerid =aps.containerid and c.workflowstepid =aps.workflowstepid 
                        where aps.apsplandetailid ='{0}' and aps.workflowstepid ='{1}' and c.isuse=0 and c.recvemployeeid is null ", drAps["apsPlanDetailID"], drAps["workflowstepid"]), null);
            sql.Clear();
            sql.AppendFormat(@"BEGIN delete apsplandetailemp ape WHERE ape.apsplandetailid = '{0}';", drAps["apsPlanDetailID"]);
            if (containerstepdispatchid != null && param["status"].Equals("1")) //已下发数据先删除派工人信息
            {
                sql.AppendFormat(@"delete containerstepdispatchdetail cd where cd.containerstepdispatchid='{0}';", containerstepdispatchid);
                var workerid = DatabaseHelper.GetSingle(string.Format(@"select workerid from containerstepdispatch where containerstepdispatchid='{0}'", containerstepdispatchid), null);
                if (workerid != null)
                {
                    sql.AppendFormat(@"update containerstepdispatch set workerid='{0}' where containerstepdispatchid='{1}';", (dtResEmp.Rows.Count == 1 ? dtResEmp.Rows[0]["employeeid"] : null), containerstepdispatchid);
                }
            }
            foreach (DataRow drEmp in dtResEmp.Rows)
            {
                sql.AppendFormat(@"INSERT INTO apsplandetailemp(ApsPlanDetailID,apsplandetailempid,employeeid,isuse) VALUES('{0}',sys_guid(),'{1}',0);",
                      drAps["apsPlanDetailID"], drEmp["employeeid"].ToString());
                if (containerstepdispatchid != null && param["status"].Equals("1")) //已下发数据新增派工人信息
                {
                    sql.AppendFormat(@"INSERT INTO containerstepdispatchdetail(containerstepdispatchid,workerid,createdate)VALUES('{0}','{1}',sysdate);",
                        containerstepdispatchid, drEmp["employeeid"].ToString());
                }
            }
            sql.AppendLine("END;");
            list.Add(sql.ToString());
            /*添加到修改记录表*/
            sql.Clear();
            sql.AppendLine(@"INSERT INTO apsplanupdaterecord(apsplanupdaterecordid,containerid,specid,workflowstepid,updateempid,updatedate,status) 
                             VALUES(");
            sql.AppendFormat("'{0}',", Guid.NewGuid().ToString());
            sql.AppendFormat("'{0}',", drAps["containerid"].ToString());
            sql.AppendFormat("'{0}',", drAps["specid"].ToString());
            sql.AppendFormat("'{0}',", drAps["workflowstepid"].ToString());
            sql.AppendFormat("'{0}',", m_UserInfo.EmployeeID);
            sql.AppendLine("sysdate,");
            sql.AppendFormat("'{0}')", param["status"]);
            list.Add(sql.ToString());
        }
        if (result.Result)
        {
            DatabaseHelper.ExecuteSqlTran(list);
            result.Message = "修改成功";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取排产列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanListByPage(HttpContext context)
    {
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        DataRow dr = dt.Rows[0];
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("mfgOrderName", dr["mfgOrderName"].ToString());//件号
        dic.Add("containerName", dr["containerName"].ToString());//批次号
        dic.Add("productName", dr["productName"].ToString());//件号
        dic.Add("specNo", dr["specNo"].ToString());//工序号
        dic.Add("startTime1", dr["startTime1"].ToString());//开始时间
        dic.Add("startTime2", dr["startTime2"].ToString());//开始时间
        dic.Add("endTime1", dr["endTime1"].ToString());//结束时间
        dic.Add("endTime2", dr["endTime2"].ToString());//结束时间
        dic.Add("apsType", dr["apsType"].ToString());//排产策略
        dic.Add("status", dr["status"].ToString());//下发状态
        dic.Add("workCenter", dr["workCenter"].ToString());//工区
        dic.Add("team", dr["team"].ToString());//班组
        dic.Add("factory", m_UserInfo.FactoryID);//分厂
        dic.Add("PageIndex", pageNumber);//
        dic.Add("PageSize", pageSize);//
        dic.Add("CurWorkflow", "");
        dic.Add("isProductLine", dr["state"].ToString());//add by longb 是否产线工序
        dic.Add("productteamid", dr["productteamid"].ToString());//件号主制单元
        dic.Add("resourceCode", dr["resourceCode"].ToString());//设备编码
        uMESProcessResult result = apsPlanDownSendBusiness.GetApsPlanListByPage(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存排产下发/回收/删除数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanDatas(HttpContext context)
    {
        string type = context.Request["type"].ToString();
        string status = context.Request["status"].ToString();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择数据" }));
            return;
        }
        if ((status.Equals("5") || status.Equals("6")) && !m_UserInfo.Roles.Contains("下发审批员"))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "在当前时间往后3天已内的数据需要【下发审批员】审核同意才能下发或回收" }));
            return;
        }
        string examineMsg = string.Empty;
        if ((type.Equals("Send") && !status.Equals("5")) || (type.Equals("ReCall") && !status.Equals("6")))
        {
            DataRow[] rowss = dt.Select("STARTTIME<'" + System.DateTime.Now.AddDays(4).ToString("yyyy-MM-dd") + " 00:00:00'");
            DataRow[] rowss2 = dt.Select("STARTTIME>='" + System.DateTime.Now.AddDays(4).ToString("yyyy-MM-dd") + " 00:00:00'");
            //DataRow[] rowss = dt.Select("STARTTIME<'2024-10-23 00:00:00'");
            //DataRow[] rowss2 = dt.Select("STARTTIME>='2024-10-23 00:00:00'");
            if (rowss.Length > 0)
            {
                DataTable newDt = rowss.CopyToDataTable();
                var examineResult = SaveApsDataToExamine(newDt, context, ref examineMsg);
                if (newDt.Rows.Count == dt.Rows.Count)
                {//全是3天以内的数据，则直接返回
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = examineResult, Message = examineMsg }));
                    return;
                }
            }
            //存在不全是3天以内的数据，则重新赋值
            if (rowss.Length > 0 && rowss2.Length > 0)
            {
                dt = rowss2.CopyToDataTable();
            }
        }

        //DataRow[] rows = dt.Select("ENDTIME<'" + System.DateTime.Now.AddDays(4).ToString("yyyy-MM-dd") + " 00:00:00'");
        //if (type.Equals("ReCall") && rows.Length > 0 && !m_UserInfo.Roles.Contains("管理员"))
        //{
        //    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "非【管理员】用户只能收回【排产结束时间】在当前时间往后3天以外的数据" }));
        //    return;
        //}
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//操作人
        dic.Add("FactoryName", m_UserInfo.Factory);//操作人分厂 add:Wangjh 20240115
        dic.Add("TeamID", m_UserInfo.TeamID);//班组
        dic.Add("type", type);//操作类型
        var sqlArrList = new ArrayList();
        if (type.Equals("ReCall") || type.Equals("Dele"))
        {
            sqlArrList = SaveApsDataToChangeTable(type, dt);
        }
        uMESProcessResult result = apsPlanDownSendBusiness.SaveApsPlanDatas(dic, dt);
        if (result.Result)
        {
            if (sqlArrList.Count > 0)
            {
                DatabaseHelper.ExecuteSqlListTran(sqlArrList);
            }
            SaveApsDataToAgree(dt, context);
        }
        result.Message += string.IsNullOrEmpty(examineMsg) ? "" : examineMsg;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 下发到手动排产
    /// </summary>
    /// <param name="context"></param>
    public void SendHandApsDatas(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未选择数据" }));
            return;
        }
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//操作人           
        uMESProcessResult result = apsPlanDownSendBusiness.SendHandApsDatas(dic, dt, m_UserInfo);

        try
        {
            //保存配套单下发json add zhunan 2025.10.10
            dic.Add("fullname", m_UserInfo.FullName);//操作人姓名
            SaveToWmsJson(dt, dic);
        }
        catch (Exception)
        {

        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private ArrayList SaveApsDataToChangeTable(string type, DataTable dt)
    {
        var arrList = new ArrayList();
        var select = @"select m.mfgordername,aps.containerid,aps.workflowstepid,'' state ,s.specno,s.specid,sb.specname,c.containername
                       ,c.productid,c.productname,c.productdescription,c.productrevision 
                        from apsplandetail aps
                        left join containercurrentinfo c on c.containerid =aps.containerid
                        left join mfgorder m on m.mfgorderid =c.mfgorderid 
                        left join workflowstep ws on ws.workflowstepid =aps.workflowstepid 
                        left join specbase sb on sb.specbaseid=ws.specbaseid
            			left join spec s on s.specid=nvl(sb.revofrcdid,ws.specid)
                        where aps.apsplandetailid='{0}' 
                        and exists (select 1 from containerstepdispatch c2 where c2.containerid =aps.containerid and c2.workflowstepid =aps.workflowstepid)
                        and exists (select 1 from sync_tablechangerecord st where st.uniquecolvalue=aps.apsplandetailid and st.operatetype='1')
                         ";
        var insert = @"insert into SYNC_TABLECHANGERECORD(ID,NEWVALUE,OPERATETYPE,UNIQUECOLVALUE)values(sys_guid(),'{0}','9','{1}')";
        var selectLastDispatch = @"SELECT * FROM (SELECT dp.* FROM containerstepdispatch dp WHERE dp.containerid='{0}' AND dp.workflowstepid='{1}' ORDER BY createdate DESC) WHERE rownum=1";

        var select2 = @"select distinct aps.apsplandetailid,c.containerstepdispatchid ,c3.customobjectitemsdesc toappid,r.resourceid,r.resourcetypeid,nvl(st.id,'0') isr
                         from apsplandetail aps
                         left join containerstepdispatch c on c.containerid =aps.containerid and c.workflowstepid =aps.workflowstepid and c.isuse =0
                         left join resourcedef r on r.resourceid =aps.resourceid
                         left join sync_tablechangerecord st on st.uniquecolvalue =r.resourceid and st.tablename =upper('resourcedef') and st.operatetype ='1'
                         left join customobject c2 on c2.customobjectid =r.productline 
                         left join customobjectitems c3 on c3.customobjectid =c2.customobjectid and c3.customobjectitemsname ='toappid'
                         where c3.customobjectitemsdesc is not null  and aps.apsplandetailid='{0}'
                         and exists (select 1 from sync_tablechangerecord st where st.uniquecolvalue=aps.apsplandetailid and st.operatetype='1')                           
                        ";

        uLMSCommonBusiness syncCommonBusiness = new uLMSCommonBusiness();
        foreach (DataRow apsdr in dt.Rows)
        {
            if (string.IsNullOrEmpty(apsdr["productline"].ToString())) continue;
            if (apsdr["CUSTOMOBJECTITEMSNAME"].ToString().Equals("CX-机匣柔性线"))
            {//机匣需要传Json文件方式的产线特殊处理
                var apsdt = DatabaseHelper.Query_ReturnDatTable(string.Format(select, apsdr["apsplandetailid"].ToString()));
                if (apsdt.Rows.Count > 0)
                {
                    DataRow dr = apsdt.Rows[0];
                    var dispatchDT = DatabaseHelper.Query_ReturnDatTable(string.Format(selectLastDispatch, dr["containerid"].ToString(), dr["workflowstepid"].ToString()));
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    dic.Add("MfgOrderName", dr["mfgordername"].ToString());//订单号
                    dic.Add("ContainerName", dr["containername"].ToString());//批次号
                    dic.Add("Description", dr["productname"].ToString());//零件名称
                    dic.Add("SpecNO", dr["specno"].ToString());//工序序号
                    dic.Add("OPDesc", dr["specname"].ToString());//工序名称
                    dic.Add("ContainerStepDispatchID", dispatchDT.Rows.Count > 0 ? dispatchDT.Rows[0]["containerstepdispatchid"].ToString() : "");//派工id
                    dic.Add("State", type.Equals("ReCall") ? "已撤销" : "已报废");//工序状态
                    var data = JsonConvert.SerializeObject(dic);
                    arrList.Add(string.Format(insert, data, apsdr["apsplandetailid"].ToString()));
                }
            }
            else
            {
                var apsdt = DatabaseHelper.Query_ReturnDatTable(string.Format(select2, apsdr["apsplandetailid"].ToString()));
                if (apsdt.Rows.Count > 0)
                {
                    string toAppId = apsdt.Rows[0]["toappid"].ToString();
                    syncCommonBusiness.InsertSyncTableChangeRecode(apsdt.AsDataView().ToTable(true, "containerstepdispatchid"), "containerstepdispatch", "containerstepdispatchid", toAppId, type.Equals("ReCall") ? 2 : 3, true);
                    syncCommonBusiness.InsertSyncTableChangeRecode(apsdt.AsDataView().ToTable(true, "apsplandetailid"), "apsplandetail", "apsplandetailid", toAppId, type.Equals("ReCall") ? 2 : 3, true);
                    if (apsdt.Rows[0]["toappid"].ToString().Equals("0"))
                    {
                        syncCommonBusiness.InsertSyncTableChangeRecode(apsdt.AsDataView().ToTable(true, "resourceid"), "resourcedef", "resourceid", toAppId, 1, true);
                        syncCommonBusiness.InsertSyncTableChangeRecode(apsdt.AsDataView().ToTable(true, "resourcetypeid"), "resourcetype", "resourcetypeid", toAppId, 1, true);
                    }
                }
            }
        }

        return arrList;
    }
    /// <summary>
    /// 
    /// </summary>
    private Boolean SaveApsDataToExamine(DataTable dt, HttpContext context, ref string resultMsg)
    {
        var status = context.Request["status"].ToString();
        var reason = context.Request["reason"].ToString();
        var remark = context.Request["remark"].ToString();
        var recordtype = status.Equals("0") ? "Aps_ToExamineSend" : "Aps_ToExamineReCall";
        var result = false;//"在当前时间往后3天已内的数据下发需要【下发审批员】审核同意才能下发";
        var arrList = new ArrayList();
        var updateApsDetailStatus = @"update apsplandetail a set a.status ='{0}' where apsplandetailid='{1}'";
        var insertLog = @"insert into writetoothersystem(writetoothersystemid,containerid, containername, createdate, parentid, recordtype,productname, workflowstepname,workflowstepid,sendxml,resxml,issuccess)
                        values(sys_guid(),'{0}','{1}',sysdate, '{2}', '{3}', '{4}','{5}','{6}','{7}','{8}','{9}')";
        try
        {
            foreach (DataRow row in dt.Rows)
            {
                //var dictionary = row.Table.Columns.Cast<DataColumn>()
                //     .ToDictionary(col => col.ColumnName, col => (row[col.ColumnName] == DBNull.Value)
                //       ? string.Empty
                //       : row[col.ColumnName]);
                arrList.Add(string.Format(updateApsDetailStatus, (status.Equals("1") ? 6 : 5), row["apsplandetailid"]));
                arrList.Add(string.Format(@"update writetoothersystem w set w.issuccess=1 where w.recordtype='{0}' and w.parentid='{1}' and w.issuccess=0", recordtype, row["apsplandetailid"]));
                arrList.Add(string.Format(insertLog, row["containerid"], row["containername"], row["apsplandetailid"], recordtype, m_UserInfo.FullName + "/" + m_UserInfo.EmployeeName, row["workflowstepname"], row["workflowstepid"], reason, remark, "0"));
            }
            if (arrList.Count > 0)
            {
                result = DatabaseHelper.ExecuteSqlListTran(arrList);
                resultMsg += ",共" + dt.Rows.Count + "条数据" + (result ? "需要【下发审批员】审核同意才能下发或回收" : "下发/回收审核失败");
            }
        }
        catch (Exception ex)
        {
            resultMsg += ",共" + dt.Rows.Count + " 数据排产下发/回收审批流程异常:" + ex.Message;
        }

        return result;
    }

    private Boolean SaveApsDataToAgree(DataTable dt, HttpContext context)
    {
        var status = context.Request["status"].ToString();
        var reason = context.Request["reason"].ToString();
        if (string.IsNullOrWhiteSpace(reason) && (status.Equals("0") || status.Equals("1"))) { return false; }
        var recordtype = status.Equals("5") ? "Aps_ToAgreeSend" : "Aps_ToAgreeReCall";
        var result = false;//
        var arrList = new ArrayList();
        var insertLog = @"insert into writetoothersystem(writetoothersystemid,containerid, containername, createdate, parentid, recordtype,productname, workflowstepname,workflowstepid,sendxml,resxml,issuccess)
                        values(sys_guid(),'{0}','{1}',sysdate, '{2}', '{3}', '{4}','{5}','{6}','{7}','{8}','{9}')";
        try
        {
            foreach (DataRow row in dt.Rows)
            {
                arrList.Add(string.Format(@"update writetoothersystem w set w.issuccess=1 where w.recordtype='{0}' and w.parentid='{1}' and w.issuccess=0", recordtype, row["apsplandetailid"]));
                arrList.Add(string.Format(insertLog, row["containerid"], row["containername"], row["apsplandetailid"], recordtype, m_UserInfo.FullName + "/" + m_UserInfo.EmployeeName, row["workflowstepname"], row["workflowstepid"], reason, "", "0"));
            }
            if (arrList.Count > 0)
            {
                result = DatabaseHelper.ExecuteSqlListTran(arrList);

            }
        }
        catch (Exception ex)
        {
        }
        return result;
    }


    private void GetUserRole(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_UserInfo.Roles.Contains("下发审批员");
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(@"select c2.customobjectitemsname,c2.customobjectitemsdesc from customobject c 
                                left join customobjectitems c2 on c2.customobjectid =c.customobjectid 
                                where c.customobjectname ='排产下发/回收原因'");
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void RefuseSendDown(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        var status = context.Request["status"].ToString();
        var reason = context.Request["reason"].ToString();
        var recordtype = status.Equals("0") ? "Aps_ToRefuseSend" : "Aps_ToRefuseReCall";
        uMESProcessResult result = new uMESProcessResult();
        var arrList = new ArrayList();
        var updateApsDetailStatus = @"update apsplandetail a set a.status ='{0}' where apsplandetailid='{1}'";
        var insertLog = @"insert into writetoothersystem(writetoothersystemid,containerid, containername, createdate, parentid, recordtype,productname, workflowstepname,workflowstepid,sendxml,issuccess)
                        values(sys_guid(),'{0}','{1}',sysdate, '{2}','{3}','{4}','{5}','{6}','{7}','{8}')";
        try
        {
            foreach (DataRow row in dt.Rows)
            {
                arrList.Add(string.Format(updateApsDetailStatus, status, row["apsplandetailid"]));
                arrList.Add(string.Format(@"update writetoothersystem w set w.issuccess=1 where w.recordtype='{0}' and w.parentid='{1}' and w.issuccess=0", recordtype, row["apsplandetailid"]));
                arrList.Add(string.Format(insertLog, row["containerid"], row["containername"], row["apsplandetailid"], recordtype, m_UserInfo.FullName + "/" + m_UserInfo.EmployeeName, row["workflowstepname"], row["workflowstepid"], reason, "0"));
            }
            if (arrList.Count > 0)
            {
                result.Result = DatabaseHelper.ExecuteSqlListTran(arrList);
                result.Message = result.Result ? "操作成功" : "操作失败";
            }
        }
        catch (Exception ex)
        {
            result.Message = "操作异常:" + ex.Message;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void GetDownLogData(HttpContext context)
    {
        string strLogSql = @"SELECT wt.CONTAINERNAME,wt.WORKFLOWSTEPNAME,a.QTY,wt.productname FULLNAME,a.STARTTIME,wt.CREATEDATE,
            decode(wt.RECORDTYPE,'Aps_ToExamineSend','下发申请','Aps_ToRefuseSend','拒绝下发','Aps_ToAgreeSend','同意下发','Aps_ToExamineReCall','回收申请','Aps_ToAgreeReCall','同意回收','拒绝回收') STATUS
            ,wt.SENDXML reason,wt.RESXML remark
            FROM writetoothersystem wt 
            LEFT JOIN APSPLANDETAIL a ON a.APSPLANDETAILID =wt.PARENTID 
            WHERE wt.RECORDTYPE LIKE 'Aps_To%' and wt.parentid='{0}'
            ORDER BY WORKFLOWSTEPNAME,CREATEDATE DESC ";
        uMESProcessResult result = new uMESProcessResult();
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(string.Format(strLogSql, context.Request["id"].ToString()));
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    //保存配套单下发json add zhunan 2025.10.10
    void SaveToWmsJson(DataTable dt, Dictionary<string, string> dict)
    {
        foreach (DataRow dr in dt.Rows)
        {
            string sql = @"
SELECT aps.apsplandetailid,cci.mfgordername,cci.containername,aps.workflowstepname,cci.workflowname,cci.workflowrevision,sp.specno,w.workcentername,rd.resourcename,
       to_char(aps.starttime,'yyyy-mm-dd hh24:mi:ss') starttime,u.attributevalue factorycode,
       t.rsnum
FROM apsplandetail aps
LEFT JOIN containercurrentinfo cci ON aps.containerid = cci.containerid
LEFT JOIN spec sp ON sp.specid = aps.specid
LEFT JOIN workcenter w ON w.workcenterid = aps.workcenterid
LEFT JOIN resourcedef rd ON rd.resourceid = aps.resourceid
LEFT JOIN userattribute u ON u.parentid = cci.originalfactoryid AND u.userattributename = '分厂代码'
INNER JOIN (
     SELECT erp.mfgordername,erp.rsnum,row_number () OVER (PARTITION BY erp.mfgordername,erp.rsnum ORDER BY erp.createdate) as rn
     FROM erp_send_material erp
) t ON t.mfgordername = cci.mfgordername AND t.rn = 1
WHERE cci.containername = '{0}' AND aps.workflowstepname = '{1}'";

            sql = string.Format(sql, dr["CONTAINERNAME"].ToString(), dr["WORKFLOWSTEPNAME"].ToString());
            DataTable dtContainer = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtContainer.Rows.Count == 0) { return; }
            Dictionary<string, object> para = new Dictionary<string, object>();
            para["reqDept"] = dtContainer.Rows[0]["factorycode"].ToString();//提请部门【必填】
            para["requester"] = dict["fullname"];//提请人【必填】
            para["bizDataNo"] = dtContainer.Rows[0]["mfgordername"].ToString();//生产订单号【必填】
            para["workFlowName"] = dtContainer.Rows[0]["workflowname"].ToString();//工艺路线名称【必填】
            para["workFlowBatch"] = dtContainer.Rows[0]["workflowrevision"].ToString();//工艺路线版本【必填】
            para["docNo"] = dtContainer.Rows[0]["rsnum"].ToString();//业务流水号【必填】
            para["batchNum"] = dtContainer.Rows[0]["containername"].ToString();//批次号【必填】
            para["engineNo"] = "";//发动机号
            para["opNumber"] = dtContainer.Rows[0]["specno"].ToString();//工序号【必填】
            para["manufacturingCell"] = dtContainer.Rows[0]["workcentername"].ToString();//工区【必填】
            para["workStation"] = dtContainer.Rows[0]["resourcename"].ToString();//设备
            para["rdDate"] = dtContainer.Rows[0]["starttime"].ToString();//需求送达日期【必填】

            //预留字段userDef01 ~ userDef10
            para["userDef01"] = "0";//领料类型，默认传0:计划内
            //para["userDef02"] = "";
            //para["userDef03"] = "";
            //para["userDef04"] = "";
            //para["userDef05"] = "";
            //para["userDef06"] = "";
            //para["userDef07"] = "";
            //para["userDef08"] = "";
            //para["userDef09"] = "";
            //para["userDef10"] = "";


            string bomSql = @"
SELECT erp.rsnum,erp.rspos,uu.uomname,
       b.bomid,bb.bomname,pml.qtyrequired * cci.qty qtyrequired,pbn.productname,p.description,p.materialtrademark,
       NVL(p.materialcode,pbn.productname) materialcode,erp.lgort,erp.productbatchno,erp.lifnr,erp.uom
FROM apsplandetail aps
LEFT JOIN containercurrentinfo cci ON aps.containerid = cci.containerid
--bom信息
LEFT JOIN bom b ON b.workflowid = cci.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
--bom工序信息
LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
LEFT JOIN spec s ON  s.specid=NVL(sb.revofrcdid, pml.specid)
LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
--子零件信息
LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
LEFT JOIN uom uu ON uu.uomid = pml.uomid
INNER JOIN erp_send_material erp ON erp.mfgordername = cci.mfgordername AND erp.productname = pbn.productname
WHERE cci.containername = '{0}' AND aps.workflowstepname = '{1}' AND aps.specid = s.specid";

            bomSql = string.Format(bomSql, dr["CONTAINERNAME"].ToString(), dr["WORKFLOWSTEPNAME"].ToString());
            DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(bomSql);
            if (dtBom.Rows.Count == 0) { return; }

            DataTable dtItems = new DataTable();
            dtItems.Columns.Add("lineNo", typeof(string));//业务流水行项目号
            dtItems.Columns.Add("itemCode", typeof(string));//物料编码
            dtItems.Columns.Add("itemName", typeof(string));//物料名称
            dtItems.Columns.Add("modelSpecs", typeof(string));//材料规格
            dtItems.Columns.Add("unit", typeof(string));//计量单位
            dtItems.Columns.Add("qty", typeof(Int32));//需求数量
            dtItems.Columns.Add("remarks", typeof(string));//备注

            dtItems.Columns.Add("LGORT", typeof(string));//库存地点
            dtItems.Columns.Add("CHARG", typeof(string));//物料批次
            dtItems.Columns.Add("LIFNR", typeof(string));//供应商编码
            
            //预留字段userDef01~userDef10
            //dtItems.Columns.Add("userDef01", typeof(string));
            //dtItems.Columns.Add("userDef02", typeof(string));
            //dtItems.Columns.Add("userDef03", typeof(string));
            //dtItems.Columns.Add("userDef04", typeof(string));
            //dtItems.Columns.Add("userDef05", typeof(string));
            //dtItems.Columns.Add("userDef06", typeof(string));
            //dtItems.Columns.Add("userDef07", typeof(string));
            //dtItems.Columns.Add("userDef08", typeof(string));
            //dtItems.Columns.Add("userDef09", typeof(string));
            //dtItems.Columns.Add("userDef10", typeof(string));

            foreach (DataRow row in dtBom.Rows)
            {
                DataRow newrow = dtItems.NewRow();
                newrow["lineNo"] = row["rspos"];//业务流水行项目号
                newrow["itemCode"] = row["materialcode"];//物料编码
                newrow["itemName"] = row["description"];//物料名称
                newrow["modelSpecs"] = row["materialtrademark"];//材料规格
                newrow["unit"] = row["uom"];//计量单位
                newrow["qty"] = Convert.ToInt32(row["qtyrequired"]);//需求数量
                newrow["remarks"] = "";
                newrow["LGORT"] = row["lgort"];//库存地点
                newrow["CHARG"] = row["productbatchno"];//物料批次
                newrow["LIFNR"] = row["lifnr"];//供应商编码
                //newrow["userDef01"] = "";
                //newrow["userDef02"] = "";
                //newrow["userDef03"] = "";
                //newrow["userDef04"] = "";
                //newrow["userDef05"] = "";
                //newrow["userDef06"] = "";
                //newrow["userDef07"] = "";
                //newrow["userDef08"] = "";
                //newrow["userDef09"] = "";
                //newrow["userDef10"] = "";
                dtItems.Rows.Add(newrow);
            }

            para["itemList"] = dtItems;

            string jsonResult = JsonConvert.SerializeObject(para);
            string ToAppID_WMS = ConfigurationManager.AppSettings["ToAppID_WMS"];

            OracleParameter[] insertParam = new OracleParameter[7];
            insertParam[0] = DatabaseHelper.NewParameter(":Methodname", "配套单下发", OracleType.VarChar);
            insertParam[1] = DatabaseHelper.NewParameter(":Json", jsonResult, OracleType.VarChar);
            insertParam[2] = DatabaseHelper.NewParameter(":Toappid", ToAppID_WMS, OracleType.VarChar);
            insertParam[3] = DatabaseHelper.NewParameter(":Tablename", "apsplandetail", OracleType.VarChar);
            insertParam[4] = DatabaseHelper.NewParameter(":Uniquecolname", "apsplandetailid", OracleType.VarChar);
            insertParam[5] = DatabaseHelper.NewParameter(":Uniquecolvalue", dtContainer.Rows[0]["apsplandetailid"].ToString(), OracleType.VarChar);
            insertParam[6] = DatabaseHelper.NewParameter(":Create_emp", dict["EmployeeID"], OracleType.VarChar);

            string insertSql = @"
INSERT INTO sync_sendto_wms(methodname,json,toappid,tablename,uniquecolname,uniquecolvalue,create_emp) 
VALUES(:Methodname,:Json,:Toappid,:Tablename,:Uniquecolname,:Uniquecolvalue,:Create_emp)";

            DatabaseHelper.ExecuteSql(insertSql, insertParam);
        }
    }
}